package tg.edu.fhh.demo.web.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import tg.edu.fhh.demo.entity.TbClass;
import tg.edu.fhh.demo.service.TbClassService;
import tg.edu.fhh.demo.web.form.TbclassForm;

@Controller
@RequestMapping(value = "/tbclass")
public class TbclassContreller {
	@Autowired
	private TbClassService tbclassService;

	@RequestMapping(value = "/manage")
	public void manage() {

	}
//, method = RequestMethod.POST
	@RequestMapping(value = "/list" )
	@ResponseBody
	public Object list(TbclassForm form) {
	Specification<TbClass> spec = buildSpec(form);
		return tbclassService.findAll(spec);
	}

	@RequestMapping(value = "/edit")
	public void edit(Integer id, ModelMap modelMap) {
		TbClass model = new TbClass();
		if (id != null) {
			model = tbclassService.findById(id);
		}
		modelMap.put("model", model);
	}
	@RequestMapping(value = "/save" )
	@ResponseBody
	public Object save(TbclassForm form) {
		TbClass model = new TbClass();
		Integer id = form.getId();
		if (id != null) {
			model = tbclassService.findById(id);
		}
		BeanUtils.copyProperties(form, model, "id");
		tbclassService.save(model);
		return "OK";
	}

	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(Integer id) {
		tbclassService.deleteById(id);
		return "OK";
	}

	@RequestMapping(value = "/search", method = RequestMethod.GET)
	public void search(TbclassForm form, ModelMap modelMap) {
		modelMap.put("model", form);
	}

	@SuppressWarnings("serial")
	private Specification<TbClass> buildSpec(TbclassForm form) {
		Specification<TbClass> spec = new Specification<TbClass>() {

			@Override
			public Predicate toPredicate(Root<TbClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				String manager= form.getManager();
				if (StringUtils.hasText(manager)) {
					rules.add(cb.like(root.get("manager"), "%" + manager + "%"));
				}
				String name = form.getName();
				if (name!= null) {
					rules.add(cb.like(root.get("name").as(String.class), "%" + name + "%"));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

}
